package com.mox.enterprise.factory;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mox.enterprise.constants.CommonConstants;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述：    工厂类
 *
 * @author mox
 */
@SuppressWarnings("unused")
public class Factory {
    /**
     * 使用单例模式
     */
    private static final Factory INSTANCE;
    private final Executor executor;
    private final Gson gson;

    static {
        INSTANCE = new Factory();
    }

    private Factory() {
        //初始化一个5个线程的线程池
        AtomicInteger count = new AtomicInteger(CommonConstants.ZERO);
        ThreadFactory threadFactory = r -> {
            String name = CommonConstants.NETWORK_PREFIX + count;
            Thread thread = new Thread(name);
            count.getAndIncrement();
            return thread;
        };

        executor = new ThreadPoolExecutor(CommonConstants.CORE_POOL_SIZE,
                CommonConstants.MAXIMUM_POOL_SIZE, CommonConstants.KEEP_ALIVE_TIME,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(CommonConstants.CAPACITY), threadFactory,
                new ThreadPoolExecutor.AbortPolicy());

        gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
    }

    /**
     * 异步上传
     *
     * @param runnable Runnable
     */
    public static void runOnAsy(Runnable runnable) {
        INSTANCE.executor.execute(runnable);
    }

    /**
     * 获取全局gson
     *
     * @return Gson
     */
    public static Gson getGson() {
        return INSTANCE.gson;
    }

}


